<!-- 合同管理->内部法人管理->新增/编辑/查看 -->
<template>
    <div class="int-box">
        <el-breadcrumb separator="/" class="bread-title">
			<el-breadcrumb-item :to="{ path: '/intLegalPersonManage' }">内部法人管理</el-breadcrumb-item>
			<el-breadcrumb-item>{{pageType}}</el-breadcrumb-item>
		</el-breadcrumb>
         <p class="type-item-title">内部法人单位信息</p>
        <el-form :rules="rules"  ref="typeForm" :model="typeForm" label-width="120px" label-position="left">
            <el-row >
                <el-col :span="10">
                    <el-form-item label="公司名称：" prop="companyName">
                        <el-input v-if="typeStatus !='view'" v-model.trim="typeForm.companyName" autocomplete="off"></el-input>
                        <span v-else>{{typeForm.companyName}}</span>
                    </el-form-item>
                    <el-form-item label="纳税人识别号：" prop="companyTaxpayer">
                        <el-input v-if="typeStatus !='view'" v-model.trim="typeForm.companyTaxpayer" autocomplete="off"></el-input>
                        <span v-else>{{typeForm.companyTaxpayer}}</span>
                    </el-form-item>
                    <el-form-item label="联系电话：" prop="companyPhone">
                        <el-input v-if="typeStatus !='view'" v-model.trim="typeForm.companyPhone" autocomplete="off" placeholder="例如“010-88888888”或者“13000000000”"></el-input>
                        <span v-else>{{typeForm.companyPhone}}</span>
                    </el-form-item>
                </el-col>
                 <el-col :span="1">&nbsp;</el-col>
                <el-col :span="13">
                    <el-form-item label="公司地址：" class="posterurl">
                        <div v-if="typeStatus !='view'" class="flex-box">
                            <el-form-item prop="companyProvince">
                                <el-select v-model.trim="typeForm.companyProvince"  placeholder="省" @change="loadCity">
                                   <el-option 
                                   v-for="(item,index) in provinceOptions" 
                                   :key="index" 
                                   :label="item.province" 
                                   :value="item.province"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop="companyCity">
                                <el-select v-model.trim="typeForm.companyCity"  @change="loadArea" placeholder="市">
                                    <el-option
                                    v-for="item in cityOptions"
                                    :key="item.cityId"
                                    :label="item.city"
                                    :value="item.city">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop="companyCounty">
                                <el-select v-model.trim="typeForm.companyCounty" placeholder="区/县">
                                    <el-option
                                    v-for="item in areaOptions"
                                    :key="item.areaId"
                                    :label="item.area"
                                    :value="item.area">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item style="width:100%" prop="companyAddress">
                                <el-input v-model.trim="typeForm.companyAddress" autocomplete="off"></el-input>
                            </el-form-item>
                        </div>
                        <span v-else>{{(typeForm.companyProvince || '') +(typeForm.companyCity|| '')+(typeForm.companyCounty||'')+(typeForm.companyAddress||'')}}</span>
                    </el-form-item>
                    <el-form-item label="法定代表人：" prop="companyRepresentative">
                        <el-input v-if="typeStatus !='view'" v-model.trim="typeForm.companyRepresentative" autocomplete="off"></el-input>
                        <span v-else>{{typeForm.companyRepresentative}}</span>
                    </el-form-item>
                    <el-form-item label="邮政编码：" prop="companyPostalcode">
                        <el-input v-if="typeStatus !='view'" v-model.trim="typeForm.companyPostalcode" autocomplete="off"></el-input>
                        <span v-else>{{typeForm.companyPostalcode}}</span>
                    </el-form-item>
                </el-col>
            </el-row>
             <el-form-item  label="备注：" prop="companyRemark">
                        <el-input v-if="typeStatus !='view'" type="textarea" :rows='6' placeholder="请输入内容" v-model.trim="typeForm.companyRemark" autocomplete="off"></el-input>
                        <span v-else>{{typeForm.companyRemark}}</span>
                </el-form-item>
		</el-form>
        <!-- 联系人信息 -->
        <contacts-table  :typeStatus="typeStatus" :insideId='insideId' :typeId='0' ref="contactsTable"></contacts-table>
        <!-- 开户行信息 -->
        <accoun-table  :typeStatus="typeStatus" :insideId='insideId' :typeId='0' ref="accounTable"></accoun-table>
        <p v-if="typeStatus !='view'" style="text-align:center">
            <el-button type="primary" v-if="typeStatus =='edit'"  @click="editSave">保存</el-button>
            <el-button type="primary" v-if="typeStatus =='add'"  @click="addSave">保存</el-button>
            <el-button type="primary"  @click="back">取消</el-button>
        </p>
        <!-- 审核记录 -> 详情页面显示 -->
        <audit-table :tableData='auditData' v-else></audit-table>
    </div>
    
</template>

<script>
import api from '@/api/apiPath'
import tableList from '../common/tableList'
import accounTable from '../common/accounTable' //引入开户信息表
import contactsTable from '../common/contactsTable' //引入联系人信息表
import auditTable from '../common/auditTable' //审核记录表
export default {
    components: {
        'table-list':tableList,
        'contacts-table':contactsTable,
        'accoun-table':accounTable,
        'audit-table':auditTable,
    },
	data () {
		return {
            auditData:[],
            typeForm:{},
            backTableData:[],//开户行数据
            contactTAbleData:[],//联系人数据
            provinceOptions:[],//省份
            cityOptions:[],//城市
            areaOptions:[],//区
            typeStatus:"",
            pageType:"",
            typeFunction:{//页面状态
                add:()=>{
                    this.pageType = "新增";
                    this.loadprovinces();
                    },
                edit:(id)=>{this.pageType = "编辑";
                    this.loadFromDetail(id);//加载表单信息
                    this.loadprovinces();
                 
                },
                view:(id)=>{ this.pageType = "详情";
                    this.loadFromDetail(id);
                }
            },
            rules:{//验证
                companyName:[
                    {required: true, trigger: ['blur', 'change'] ,validator: (rule, value, callback) => {
                            if(!value) {
                                    return callback(new Error('请输入公司名称'));
                            }
                            if(value.length>30){
                                    return callback(new Error('公司名称长度不能大于30'));
                            }
                            callback();
                        }
                    }
                ],
                
                companyTaxpayer:[
                     { required: true, trigger: ['blur', 'change'] ,validator:(rule, value, callback)=>{
                            const reg =  /^[0-9A-Z]{15,}$/;
                            if(!value) return callback(new Error("请输入纳税人识别号"))
                            if((value.length !=15 && value.length !=17 && value.length !=18 && value.length !=20) || !reg.test(value))
                                return callback(new Error("请输入正确格式的纳税人识别号"))
                          
                            callback()
                            
                        } 
                    },
                ],
                companyRepresentative:[
                    { required: true, message: '请输入法定代表人', trigger: ['blur', 'change']  },
                    { min: 0, max: 20, message: '法定代表长度不能大于20', trigger: ['blur', 'change'] }
                ],
                companyPhone:[
                    { required: true, trigger: ['blur', 'change'] ,validator:(rule, value, callback)=>{
                            const reg = /^0\d{2,3}-?\d{7,8}$|^1\d{10}$/;
                            if(!value){
                                callback(new Error("请输入联系电话"))
                            }else if(!reg.test(value)){
                                callback(new Error("请输入正确的电话号码"))
                            }else{
                                callback()
                            }
                        } 
                    }
                ],
                companyPostalcode:[
                    {required: false,trigger: ['blur', 'change'] ,validator: (rule, value, callback) => {
                            const reg = /^[0-9]{6}$/g;
                            if(!value) return callback();
                            if(!reg.test(value)){
                                callback(new Error("请输入正确的邮政编码"))
                            }else{
                                callback();
                            }
                        }
                    }
                ],
                companyRemark:[
                    {required: false, min: 0, max: 100, message: '长度不得超过100个字符', trigger: ['blur', 'change'] },
                ],
                companyProvince: [
                   { required: true, message: '请选择省份', trigger: ['blur', 'change']}
                ],
                companyCity: [
                   { required: true, message: '请选择城市', trigger: ['blur', 'change']}
                ],
                companyCounty: [
                   { required: true, message: '请选择区县', trigger: ['blur', 'change']}
                ],
                companyAddress: [
                    { required: true, message: '请输入详细地址', trigger: ['blur', 'change']  },
                    { min: 0, max: 50, message: '长度不得超过50个字符', trigger: ['blur', 'change'] }
                ],

            },
        }
    },
    methods:{
        addSave(){
            let contactList = this.$refs['contactsTable'].returnTabel();
            let backList = this.$refs['accounTable'].returnTabel();
            if(!contactList.length) {
                this.$alert('请添加联系人').then().catch();
                return ;
            }
            if(!backList.length) {
                this.$alert('请添加开户行').then().catch();
                return ;
            }
            this.$refs.typeForm.validate((valid)=>{
                if(!valid){
                    return
                }
                let params = {
                    inside:this.typeForm,
                    contact:contactList,
                    bank:backList,
                }
                
                this.axios.post(api.ADDINITCOMPANY,params).then((res)=>{
                    if(res.data.code==200){
                        this.$alert("保存成功", '提示', {
                                type: 'success',
                                confirmButtonText: '确定',
                                callback: action => {
                                        this.$router.push({path:"/intLegalPersonManage"})
                                    }
                        });
                    }
                }).catch((error)=>{
                        console.log(error)
                })
            })
            
        },
        editSave(){
            let contactList = this.$refs['contactsTable'].returnTabel();
            let backList = this.$refs['accounTable'].returnTabel();
            if(!contactList.length) {
                this.$alert('请添加联系人').then().catch();
                return ;
            }
            if(!backList.length) {
                this.$alert('请添加开户行').then().catch();
                return ;
            }
            this.$refs.typeForm.validate((valid)=>{
                if(!valid){
                    return
                }
                let params = {
                    id:this.insideId,
                    inside:this.typeForm,
                }
                
                this.axios.post(api.EDITINITCOMPANY,params).then((res)=>{
                    if(res.data.code==200){
                        this.$alert("编辑成功", '提示', {
                                type: 'success',
                                confirmButtonText: '确定',
                                callback: action => {
                                        this.$router.go(-1);
                                    }
                        });
                    }
                }).catch((error)=>{
                        console.log(error)
                })
            })
        },
        back(){
            this.$router.go(-1);
        },
        //加载当前页面表单详情
        loadFromDetail(id){
            this.axios.post(`${api.INITCOMPANYDETAIL}`,{id:id}).then(res => {
                if (res.data.code == 200) {
                    let thisFrom  = res.data.data.inside;
                    delete thisFrom.updateId
                    delete thisFrom.updateName
                    delete thisFrom.updateTime
                    delete thisFrom.userId
                    delete thisFrom.userName
                    this.typeForm = thisFrom;
                    this.backTableData = res.data.data.back;
                    this.contactTAbleData = res.data.data.contact;
                    this.auditData = res.data.data.operation;
                    
                }
            })
        },
        //获取省
        loadprovinces(){
             this.axios.get(api.GETPROVINCES).then(res => {
                    if (res.data.code == 200) {
                       this.provinceOptions = res.data.data;
                       
                    }
                })
        },
        //获取市
        loadCity(province){
            let thisObj = this.provinceOptions.find(item=>{
                return province === item.province;
            })
            this.$set(this.typeForm,'companyCity',null);
            this.$set(this.typeForm,'companyCounty',null);
            this.axios.get(`${api.GETCITY}/${thisObj.provinceid}`).then(res => {
                    if (res.data.code == 200) {
                       this.cityOptions = res.data.data.cityList;
                       
                    }
                })
        },
        //获取区
        loadArea(city){
             let thisObj = this.cityOptions.find(item=>{
                return city === item.city;
            })
            this.$set(this.typeForm,'companyCounty',null);
            this.typeForm.companyCityCode = thisObj.cityId;
            this.axios.get(`${api.GETAREA}/${thisObj.cityId}`).then(res => {
                    if (res.data.code == 200) {
                       this.areaOptions = res.data.data.cityArealist;
                       
                    }
            })
        }

 
	
	},
	created () {
       let {pageType,insideId} = this.$route.query;
       //更改页面状态（新增/编辑/查看）
       this.typeStatus = pageType;
       this.insideId = insideId;
       //执行该状态init()
       this.typeFunction[pageType](insideId);
    },
	destroyed() {
		
	},
	filters: {

	}
}

</script>

<style lang="stylus" >
.int-box{
    p{
        margin:0;
        padding:20px 0;
    }
  .type-item-title{
        font-size:18px;
        color:#303133;
        font-weight :700;
        margin-bottom:30px;
        border-bottom: 1px solid #ddd;
        
  }
  .back-btn{
      padding:30px 0;
      text-align :center;
  }
  .flex-box{
    display:flex;
 }
 .flex-box>*{
    margin-right :10px;
 }
}
    
 .posterurl .el-form-item__label:before{
        content: '*';
        color: #f56c6c;
        margin-right: 4px;
    }

</style>
